﻿using System.Linq;
using DataModel.Models;

namespace DataModel.Managers.SubManage
{
    public class AuthenticationManager
    {
        private readonly UniversityPortalEntities _entityModel;

        public AuthenticationManager()
        {
            _entityModel = new UniversityPortalEntities();
        }

        /// <summary>
        /// Verify user login and password
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool IsValid(string login, string password)
        {
            bool res = false;
            User user = _entityModel.Users.FirstOrDefault(usr => usr.login == login);
            if (user != null)
            {
                if ((new Hasher()).VerifyMd5Hash(password, user.password))
                {
                    res = true;
                }
            }
            return res;
        }

        /// <summary>
        /// Returns welcom string
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public string GetLoginInfoString(string login)
        {
            string loginInfoString = null;
            var userManager = new UserManager();
            UserModel user = userManager.GetUser(login);
            if (user != null)
            {
                loginInfoString = string.Format("{0} {1} {2}", user.LastName, user.FirstName, user.FamilyName);
                Student student = _entityModel.Students.FirstOrDefault(studentItem => studentItem.userID == user.ID);
                if (student != null)
                {
                    loginInfoString = string.Format("{0}, group {1}", loginInfoString, student.Group.number);
                }
            }
            return loginInfoString;
        }
    }
}
